package controller

import (
	"gitee.com/DonHz/qimi/bluebell/logic"
	"gitee.com/DonHz/qimi/bluebell/models"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
)

func CreatePostHandler(c *gin.Context) {
	// 1.获取参数
	var req=new(models.PostArticle)
	if err:=c.ShouldBindJSON(req); err!=nil {
		zap.L().Error("bind json failed when post article.", zap.Error(err))
		ResponseError(c, CodeInvalidParam)
		return
	}
	authorId, err:=getUserId(c)
	if err!=nil {
		zap.L().Error("get UserId failed when post article.", zap.Error(err))
		ResponseError(c, CodeNeedLogin)
		return
	}
	req.AuthorId=authorId
	// 2.创建帖子
	if err:=logic.CreateArticle(req); err!=nil {
		zap.L().Error("logic.CreateArticle() failed.", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	// 3.返回响应
	ResponseSuccess(c, nil)
}

func ArticleDetailHandler(c *gin.Context) {
	idStr:=c.Param("id")
	if len(idStr)==0 {
		zap.L().Error("get article id failed")
		ResponseError(c, CodeInvalidParam)
		return
	}
	aid, err:=strconv.ParseInt(idStr, 10, 64)
	if err!=nil {
		zap.L().Error("strconv article id to int64 failed",zap.Error(err))
		ResponseError(c, CodeInvalidParam)
		return
	}
	data, err:=logic.GetArticleById(aid)
	if err!=nil {
		zap.L().Error("get article by id failed",zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, &data)
}

func GetArticleListHandler(c *gin.Context) {
	data, err:=logic.GetArticleList()
	if err!=nil {
		zap.L().Error("logic.GetArticleList() failed",zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}